package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"macapp/models"
	"net/url"
	"strconv"
	"unsafe"
)

type AdminUsersController struct {
	beego.Controller
}

func (a *AdminUsersController) Index() {
	a.TplName = "admin/users.html"
}

func (a *AdminUsersController) GetAll() {
	var usersjson models.VipusersJson
	var users []models.Vipusers

	page := a.GetString("page")
	limit := a.GetString("limit")
	int_page, _ := strconv.Atoi(page)
	int_limit, _ := strconv.Atoi(limit)

	qs := models.O.QueryTable(new(models.Vipusers))
	qs.Limit(int_limit, (int_page-1)*int_limit).OrderBy("-id").All(&users)

	usersjson.Code = 0
	usersjson.Msg = ""
	usersjson.Count = GetUsersCounts()
	usersjson.Data = users
	a.Data["json"] = &usersjson
	a.ServeJSON()
}

func (a *AdminUsersController) Edit(){
	//
	var user models.Vipusers

	enEscapeUrl,_:=url.QueryUnescape(a.Ctx.Input.Param(":userjson"))
	//fmt.Println(">>>>>>"+enEscapeUrl)
	json.Unmarshal([]byte(enEscapeUrl),&user)

	a.Data["id"]=user.Id
	a.Data["useranme"]=user.Username
	a.Data["email"]=user.Email
	a.Data["remaining"]=user.Remaining
	a.Data["password"]=user.Password
	a.Data["status"]=user.Status
	a.TplName = "admin/users-edit.html"
}

func (a *AdminUsersController) Update()  {
	var user models.Vipusers
	update_restful:=a.GetString("restful")
	json.Unmarshal([]byte(update_restful),&user)

	if user.Checkbox=="on"{
		user.Status="启用"
	}else {
		user.Status="禁用"
	}

	if _, err := models.O.Update(&user,"Username","Email","Remaining","Status","Password"); err == nil {
		fmt.Println("更新:"+user.Id+">>>>>"+user.Username+">>>>>"+user.Status)
	}else{
		fmt.Println(err)
	}
	//models.O.Update(&user,"Username","Email","Remaining","Status","Password")
	a.Ctx.WriteString("success")
}

func GetUsersCounts() int {
	int64_cnt, _ := models.O.QueryTable(new(models.Vipusers)).Count()
	//int64 转int
	cnt := *(*int)(unsafe.Pointer(&int64_cnt))
	return cnt
}
